{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "from pytorch_transformers import BertTokenizer, BertModel, BertForMaskedLM"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "The pre-trained model you are loading is a cased model but you have not set `do_lower_case` to False. We are setting `do_lower_case=False` for you but you may want to check this behavior.\n"
     ]
    }
   ],
   "source": [
    "tokenizer = BertTokenizer.from_pretrained('bert-base-multilingual-cased')\n",
    "model = BertModel.from_pretrained('bert-base-multilingual-cased')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "example_en = \"It's International Dog Day!\"\n",
    "example_ru = \"Это Международный День Собаки!\"\n",
    "\n",
    "encoded_examples = [torch.tensor(tokenizer.encode(ex)).unsqueeze(0) \n",
    "                    for ex in [example_en, example_ru]]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"It's International Dog Day!\""
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Decoding works similarly - word pieces are concatenated automatically\n",
    "tokenizer.decode([int(tok) for tok in encoded_examples[0][0]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "torch.Size([7, 768])"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Set model to eval to deactivate dropout\n",
    "model.eval()\n",
    "\n",
    "example_hidden_states = [model(ex)[0][0] for ex in encoded_examples]\n",
    "\n",
    "# 7 WordPieces, 768 weights\n",
    "example_hidden_states[0].shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "mlm_model = BertForMaskedLM.from_pretrained('bert-base-multilingual-cased')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "BertOnlyMLMHead(\n",
       "  (predictions): BertLMPredictionHead(\n",
       "    (transform): BertPredictionHeadTransform(\n",
       "      (dense): Linear(in_features=768, out_features=768, bias=True)\n",
       "      (LayerNorm): BertLayerNorm()\n",
       "    )\n",
       "    (decoder): Linear(in_features=768, out_features=119547, bias=False)\n",
       "  )\n",
       ")"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# This model includes the prediction layer \n",
    "mlm_model.cls"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "tokenized_text = tokenizer.tokenize('I love my pets!')\n",
    "masked_index = 3\n",
    "tokenized_text[masked_index] = '[MASK]'\n",
    "indexed_tokens = tokenizer.convert_tokens_to_ids(tokenized_text)\n",
    "segments_tensors = torch.tensor([0] * len(tokenized_text))\n",
    "tokens_tensor = torch.tensor([indexed_tokens])\n",
    "\n",
    "# Convert inputs to PyTorch tensors\n",
    "model.eval()\n",
    "\n",
    "# Encode inputs to hidden states using regular BERT\n",
    "with torch.no_grad():\n",
    "    encoded_layers, _ = model(tokens_tensor, segments_tensors)\n",
    "\n",
    "# Attempt to predict masked token using BERT for MLM prediction\n",
    "mlm_model.eval()\n",
    "\n",
    "with torch.no_grad():\n",
    "    predictions = mlm_model(tokens_tensor, segments_tensors)\n",
    "    \n",
    "predicted_index = torch.argmax(predictions[0][0, masked_index]).item()\n",
    "predicted_token = tokenizer.convert_ids_to_tokens([predicted_index])[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'heart'"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "predicted_token"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.2"
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
